package server;

import static server.RLM_Server.databaseModul;

import java.util.Enumeration;

import server_commands.Command;
import server_commands.LOGOUTCommand;
import connection_modul.DatabaseConnection;

/**
 * Thread koji periodicno proverava status konekcije sa klijentima.
 * 
 * @author Uros Krkic
 */
public class ActiveConnectionsChecker extends Thread {

	private static final int SLEEP_TIME	= 5000;
	
	private RLM_Server rlmServer = null;
	
	public ActiveConnectionsChecker(RLM_Server rlmServer) {
		this.rlmServer = rlmServer;
	}
	
	
	@Override
	public void run() {
		
		while ( rlmServer != null && rlmServer.isStarted() ) {
			
			try {
				Thread.sleep(SLEEP_TIME);
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
			
			Enumeration<String> keys = RLM_Server.activeConnections.keys();
			
			while ( keys.hasMoreElements() ) {
				String key = keys.nextElement();
				
				ServerSocketConnection ssc = RLM_Server.activeConnections.get(key);
				if (ssc == null) {
					// logout
					Command logoutCommand = new LOGOUTCommand(key);
					DatabaseConnection dbConnection = new DatabaseConnection(databaseModul);
					logoutCommand.executeCommand(ssc, dbConnection);
					RLM_Server.activeConnections.remove(key);
				}
				
				try {
					ssc.getSocket().getOutputStream().write("SERV_PING\n".getBytes());
					ssc.getSocket().getOutputStream().flush();
				} catch (Exception e) {
//					e.printStackTrace();
					Command logoutCommand = new LOGOUTCommand(key);
					DatabaseConnection dbConnection = new DatabaseConnection(databaseModul);
					logoutCommand.executeCommand(ssc, dbConnection);
					RLM_Server.activeConnections.remove(key);
				}
			}
		}
		
	}
	
}
